package captchax

import (
	"time"

	"gitee.com/workits/pkgs/cachex"
	"github.com/mojocn/base64Captcha"
)

type store struct {
	cache     cachex.Cache
	exMinutes time.Duration
}

func NewStore(cfg Config, cache cachex.Cache) base64Captcha.Store {
	return &store{
		cache:     cache,
		exMinutes: cfg.ExMinutes,
	}
}

func (s *store) Set(id string, value string) error {
	return s.cache.Set(id, value, s.exMinutes*time.Minute)
}

func (s *store) Get(id string, clear bool) string {
	if result, err := s.cache.Get(id); err != nil {
		return ""
	} else {
		if clear {
			_ = s.cache.Del(id)
		}
		return result
	}
}

func (s *store) Verify(id, answer string, clear bool) bool {
	value := s.Get(id, clear)
	if len(value) == 0 {
		return false
	}
	return value == answer
}
